<template>
  <div>
    <Card title="用户查询" :bordered="false" :dis-hover="true">
      <div style="float: right" slot="extra">
        <Button size="small" type="primary" icon="ios-search" @click="search"
          >搜索</Button
        >
      </div>
      <Form
        inline
        label-position="right"
        :label-width="100"
        :model="searchParams"
      >
        <Row>
          <Col span="6">
            <FormItem label="用户名">
              <Input
                clearable
                placeholder="请输入用户名"
                v-model="searchParams.username"
              />
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="真实姓名">
              <Input
                clearable
                placeholder="请输入真实姓名"
                v-model="searchParams.real_name"
              />
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="联系电话">
              <Input
                clearable
                placeholder="请输入联系电话"
                v-model="searchParams.phone"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Card>
    <Card :bordered="false" :dis-hover="true">
      <p slot="title">用户列表</p>
      <div slot="extra">
        <span class="card-extra-item">
          <Icon size="24" color="#19be6b" type="ios-leaf" />正常
        </span>
        <span class="card-extra-item">
          <Icon size="24" color="#ff9900" type="ios-leaf" />冻结
        </span>
        <Button
          type="primary"
          size="small"
          class="card-extra-item"
          @click="createUser = true"
          >添加</Button
        >
      </div>
      <Table
        highlight-row
        :columns="userColumns"
        :data="userData"
        border
        size="small"
      >
        <template slot-scope="{ row }" slot="gender">
          <div>{{ row.gender === "male" ? "男" : "女" }}</div>
        </template>
        <template slot-scope="{ row }" slot="is_active">
          <Icon
            v-if="row.is_active"
            size="24"
            color="#19be6b"
            type="ios-leaf"
          />
          <Icon v-else size="24" color="#ff9900" type="ios-leaf" />
        </template>
        <template slot-scope="{ row }" slot="action">
          <Button
            size="small"
            type="text"
            style="color: #2d8cf0"
            @click="showEditUserModal(row)"
            >编辑</Button
          >
          <Button
            size="small"
            type="text"
            style="color: #2d8cf0"
            @click="resetPwd(row.id)"
            >重置密码</Button
          >
          <template v-if="row.id !== $store.state.user.id">
            <Button
              size="small"
              type="text"
              :style="'color:' + (row.is_active ? '#ff9900' : '#ed4014')"
              @click="activeUser(row)"
              v-if="!row.is_system"
              >{{ row.is_active ? "冻结" : "激活" }}</Button
            >
            <Poptip
              title="确定要删除吗?"
              confirm
              transfer
              @on-ok="handleDeleteUserSubmit(row.id) && !row.is_system"
            >
              <Button
                size="small"
                type="text"
                style="color: #ed4014"
                v-if="!row.is_system"
                >删除</Button
              >
            </Poptip>
          </template>
        </template>
      </Table>
      <Page
        transfer
        :total="page.total"
        :current="page.current"
        :page-size="page.pageSize"
        :page-size-opts="page.pageSizeOpts"
        size="small"
        show-elevator
        show-sizer
        show-total
        prev-text="上一页"
        next-text="下一页"
        style="margin-top: 15px"
        @on-change="change"
        @on-page-size-change="pageSizeChange"
      />
    </Card>

    <UserCreate
      :createUser.sync="createUser"
      @initUserTable="search"
    ></UserCreate>
    <UserEdit
      :editUser.sync="editUser"
      @initUserTable="search"
      :user="user"
    ></UserEdit>
  </div>
</template>

<script>
import {
  resetPwd,
  activeUser,
  getUsers,
  deleteUser,
} from "@/api/HttpAutoTestService/user";
import UserCreate from "@/view/components/HttpAutoTestService/user/user-create";
import UserEdit from "@/view/components/HttpAutoTestService/user/user-edit";

export default {
  name: "user",
  components: {
    UserCreate,
    UserEdit,
  },
  data() {
    return {
      createUser: false,
      editUser: false,
      searchParams: {
        username: "",
        real_name: "",
        phone: "",
      },
      user: {},
      userColumns: [
        {
          type: "index",
          width: 60,
          align: "center",
        },
        {
          title: "用户名",
          key: "username",
          width: 150,
        },
        {
          title: "真实姓名",
          key: "real_name",
          width: 150,
        },
        {
          title: "性别",
          slot: "gender",
          align: "center",
          width: 80,
        },
        {
          title: "联系电话",
          key: "phone",
          width: 150,
        },
        {
          title: "电子邮箱",
          key: "email",
          width: 180,
        },
        {
          title: "创建时间",
          key: "create_time",
          align: "center",
          width: 180,
        },
        {
          title: "备注",
          key: "remark",
          tooltip: true,
        },
        {
          title: "状态",
          slot: "is_active",
          align: "center",
          width: 65,
        },
        {
          title: "操作",
          slot: "action",
          align: "center",
          width: 245,
        },
      ],
      userData: [],
      page: {
        current: 1,
        total: 0,
        pageSize: 50,
        pageSizeOpts: [10, 30, 50, 100, 200],
      },
    };
  },
  mounted() {
    this.search();
  },
  methods: {
    search(page) {
      let data = {
        name: this.searchParams.name,
        real_name: this.searchParams.real_name,
        phone: this.searchParams.phone,
        page: 1,
        page_size: this.page.pageSize,
      };
      if (typeof page == "number") {
        data.page = page;
      }
      this.page.current = data.page;

      getUsers(data)
        .then((res) => {
          const data = res.data;
          this.userData = data.results;
          this.page.total = data.count;
          if (data.next === null) {
            this.page.current = Math.ceil(this.page.total / this.page.pageSize);
          }
          if (data.previous === null) {
            this.page.current = 1;
          }
        })
        .catch((err) => {
          this.$Modal.error({
            title: "系统异常，请联系管理员……",
            content: JSON.stringify(err),
            closable: true,
          });
        });
    },

    resetPwd(id) {
      resetPwd(id)
        .then((res) => {
          if (res.status === 200) {
            this.$Message.info(
              `重置成功，新密码：${res.data.password}，请妥善保管！！！`
            );
          } else {
            this.$Message.error("重置失败");
          }
        })
        .catch((err) => {
          this.$Modal.error({
            title: "系统异常，请联系管理员……",
            content: JSON.stringify(err),
            closable: true,
          });
        });
    },

    activeUser(row) {
      const id = row.id;
      if (id === this.$store.state.user.id) {
        this.$Message.info("不能冻结当前登录用户");
      } else {
        let data = {
          id: row.id,
          is_active: !row.is_active,
        };
        activeUser(data)
          .then((res) => {
            if (res.status === 200) {
              if (row.is_active) {
                this.$Message.info("冻结成功");
              } else {
                this.$Message.info("激活成功");
              }
              this.search();
            } else {
              if (row.is_active) {
                this.$Message.info("冻结失败");
              } else {
                this.$Message.info("激活失败");
              }
            }
          })
          .catch((err) => {
            this.$Modal.error({
              title: "系统异常，请联系管理员……",
              content: JSON.stringify(err),
              closable: true,
            });
          });
      }
    },

    handleDeleteUserSubmit(id) {
      if (id === this.$store.state.user.id) {
        this.$Message.info("不能删除当前登录用户");
      } else {
        deleteUser(id)
          .then((res) => {
            if (res.status === 204) {
              this.$Message.info("删除成功");
              this.search();
            } else {
              this.$Message.error("删除失败");
            }
          })
          .catch((err) => {
            this.$Modal.error({
              title: "系统异常，请联系管理员……",
              content: JSON.stringify(err),
              closable: true,
            });
          });
      }
    },

    showEditUserModal(row) {
      let { id, username, real_name, gender, phone, email, remark } = row;
      this.user = {
        id,
        username,
        real_name,
        gender,
        phone,
        email,
        remark,
      };
      this.editUser = true;
    },

    change(val) {
      this.page.current = val;
      this.search(val);
    },

    pageSizeChange(val) {
      this.page.pageSize = val;
      this.search();
    },
  },
};
</script>

<style scoped>
.ivu-form-item {
  width: 100%;
}
</style>
